<?php
// +----------------------------------------------------------------------
// | QSCMS
// +----------------------------------------------------------------------
// | Copyright (c)  2025 https://www.qqss.net All rights reserved.
// +----------------------------------------------------------------------
// | Licensed QSCMS is not free software, commercial use must purchase official license from official website to avoid unnecessary legal disputes.
// +----------------------------------------------------------------------
// | Author: Contract 990504246@qq.com
// +----------------------------------------------------------------------

namespace app\common\model;

use think\Model;

class GoodsContentChapter extends Model
{
    protected $autoWriteTimestamp = true;

    /**
     * 商品关联
     */
    public function goods()
    {
        return $this->belongsTo('Goods', 'goods_id');
    }

    /**
     * 分组关联
     */
    public function group()
    {
        return $this->belongsTo('GoodsContentGroup', 'group_id');
    }

    /**
     * 处理章节内容授权
     * @param string $content 原始内容
     * @param bool $hasAuth 是否有权限
     * @return string 处理后的内容
     */
    public static function handleAuthContent($content, $hasAuth = false)
    {
        return $hasAuth ? $content : '需要购买后查看章节内容';
    }

    /**
     * 获取指定商品的所有章节
     * @param int $goodsId 商品ID
     * @param bool $withContent 是否包含内容
     * @return \think\Collection
     */
    public static function getGoodsChapters($goodsId, $withContent = false)
    {
        $query = self::where('goods_id', $goodsId)
            ->order('sort asc, id asc');

        if (!$withContent) {
            $query->field('id, goods_id, group_id, title, sort, is_free');
        }

        return $query->select();
    }

    /**
     * 检查章节是否收费 - 简化逻辑
     * @return bool
     */
    public function isCharged()
    {
        // 如果章节设置为免费，则不收费
        if ($this->is_free) {
            return false;
        }

        // 默认情况下，根据商品价格判断
        return $this->goods && $this->goods->price > 0;
    }

    /**
     * 检查用户是否有权限查看章节
     * @param int $userId 用户ID
     * @return bool
     */
    public function canUserView($userId)
    {
        if (!$userId) {
            return false;
        }

        $user = User::find($userId);
        if (!$user) {
            return false;
        }

        // 如果章节不收费，则可以查看
        if (!$this->isCharged()) {
            return true;
        }

        // 检查用户是否有权限查看（简化为检查是否购买了商品）
        return $user->hasPurchased($this->goods_id);
    }

    public function getUrlAttr()
    {
        return _url_('goods.chapter', ['id' => $this->id]);
    }
}